import re

from rest_framework import serializers

from apps.goods.models import GoodsVisitCount
from apps.users.models import User


class GoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsVisitCount
        fields = ('count', 'category')


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email')


class UserCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email')

        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机错误')
        return value

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user
